package solution;

/**
 * Created by wangxingsheng on 2019/8/9.
 * 给出两个 非空 的链表用来表示两个非负的整数。其中，它们各自的位数是按照 逆序 的方式存储的，并且它们的每个节点只能存储 一位 数字。
 * <p>
 * 如果，我们将这两个数相加起来，则会返回一个新的链表来表示它们的和。
 * <p>
 * 您可以假设除了数字 0 之外，这两个数都不会以 0 开头。
 * <p>
 * <p>
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/add-two-numbers
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);
        int[] diff = new int[]{0};
        sum(res, l1.val + l2.val, diff);
        res = res.next;
        ListNode head = res;
        while (l1.next != null && l2.next != null) {
            l1 = l1.next;
            l2 = l2.next;
            sum(res, l1.val + l2.val, diff);
            res = res.next;
        }
        while (l1.next != null) {
            l1 = l1.next;
            sum(res, l1.val, diff);
            res = res.next;
        }
        while (l2.next != null) {
            l2 = l2.next;
            sum(res, l2.val, diff);
            res = res.next;
        }
        if (diff[0] > 0) {
            res.next = new ListNode(1);
        }
        return head;
    }

    private void sum(ListNode node, int sum, int[] diff) {
        sum = sum + diff[0];
        if (sum >= 10) {
            node.next = new ListNode(sum - 10);
            diff[0] = 1;
        } else {
            node.next = new ListNode(sum);
            diff[0] = 0;
        }
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}
